package com.winai.launcher.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;

import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.Application;
import com.winai.launcher.base.db.DB_Common;
import com.winai.launcher.bean.db.Device;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.manager.DeviceManager;
import com.winai.launcher.manager.NetworkManager;
import com.winai.launcher.manager.UpgradeProgressManager;
import com.winai.launcher.manager.WindowTipManager;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.utils.AppExecutors;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.NetworkUtils;
import com.winai.launcher.utils.NotifyReceiverUtils;
import com.winai.launcher.view.LogicActivity;
import com.yhao.floatwindow.FloatWindow;

/**
 * @auth 康少
 * @date 2020/12/17
 * @desc 网络变化监听服务
 */
public class NetworkService extends Service {
    private Context context = this;

    public NetworkService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        logic();
        return super.onStartCommand(intent, flags, startId);
    }

    private void logic() {
        if (!NetworkUtils.hasNetwork(context)) {
            LogUtils.d("网络改变-无网");
            NetworkManager.getInstance(context).setConnectedWifi(null);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!NetworkUtils.hasNetwork(context)) {
                        //无网络 通知全局弹窗
                        WindowTipManager.getInstance(context).showTip();
                        NotifyReceiverUtils.notifyPulldownReceiver(context, false);
                    }
                }
            }, 5000);
        } else {
            LogUtils.d("网络改变-有网");
            //有网络
            WindowTipManager.getInstance(context).dismissTip();

            DB_Common dbCommon = new DB_Common(context);
            String isFirst = dbCommon.get("isFirstOpenApp");
            if (!TextUtils.isEmpty(isFirst)) {
                //首次打开APP，未引导完成的话不允许下拉。
                if (FloatWindow.get(UpgradeProgressManager.WINDOW_TAG) == null
                        || !FloatWindow.get(UpgradeProgressManager.WINDOW_TAG).isShowing()) {
                    NotifyReceiverUtils.notifyPulldownReceiver(context, true);
                }
            }
            //判断是否显示激活二维码
            AppExecutors.getInstance().networkIO().execute(this::checkLogin);
        }
        GlobalPublisher.Notify(GlobalPublisher.CHANGE_WIFI);//通知网络改变
        stopSelf();//执行结束后关闭服务，防止内存泄漏
    }

    private void checkLogin() {
        //首次打开APP，显示引导页
        DB_Common dbCommon = new DB_Common(this);
        String isFirst = dbCommon.get("isFirstOpenApp");
        Device device = DeviceManager.loadDeviceFromDB(BaseUtils.getDeviceId());
        LogUtils.e("isFirst = " + isFirst);
        LogUtils.d("device != null && device.isBindStatus() =" + (device == null || !device.isBindStatus()));
        if (!TextUtils.isEmpty(isFirst) && (device == null || !device.isBindStatus())) {
            /* 跳转客户的激活app */
            try {
                Intent intent = new Intent();
                intent.setClassName("com.aiyisheng.speaker"
                        , "com.aiyisheng.speaker.user.activation.ActivationActivity");
                intent.putExtra("deviceId", BaseUtils.getDeviceId());//新增deviceId参数
                while (Application.getHomeActivity() == null) {
                    Thread.sleep(1000);
                    LogUtils.d("等待设置HomeActivity");
                }
                Application.getHomeActivity().startActivityForResult(intent, LogicActivity.RESULT_CODE);
                LogUtils.d("跳转艾益生激活二维码页面，deviceId = " + BaseUtils.getDeviceId());
                /*((BaseActivity) mContext).overridePendingTransition(0, 0);*/
                NotifyReceiverUtils.notifyLauncherStart(context);
                NotifyReceiverUtils.notifyPulldownReceiver(context, false);
                NotifyReceiverUtils.notifyToggleWakeUpReceiver(context, false);
            } catch (Exception e) {
                e.printStackTrace();
                if (Application.getHomeActivity() != null) {
                    Application.getHomeActivity().runOnUiThread(() -> ToastKs.show(context, "您还没有安装小艾音箱"));
                }
            }
        }
    }
}